package com.cuhk.gulimall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.cuhk.common.to.es.SkuEsModel;
import com.cuhk.gulimall.search.config.ElasticSearchConfig;
import com.cuhk.gulimall.search.constant.EsConstants;
import com.cuhk.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esRestClient;

    @Override
    public boolean productStartUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 保存到es

        // Step1: 给ES中建立一个索引
        // 通过kibana执行product-mapping.txt中的代码完成

        // Step2: 构建ES存储数据的请求
        // 批量操作
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(skuEsModel -> {
            // 创建一个存储数据的index请求
            IndexRequest indexRequest = new IndexRequest(EsConstants.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });

        // Step3 向ES发送同步的数据添加请求
        BulkResponse bulkResponse = esRestClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // Step4 处理错误
        boolean b = bulkResponse.hasFailures();
        if(b) {
            List<String> collect = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商品上架错误: {}", collect);
        }
        return !b;
    }

}
